package io.github.xbeeant.eoffice.rest;

import io.github.xbeeant.antdesign.TableResponse;
import io.github.xbeeant.core.ApiResponse;
import io.github.xbeeant.core.ErrorCodeConstant;
import io.github.xbeeant.eoffice.model.*;
import io.github.xbeeant.eoffice.service.*;
import io.github.xbeeant.eoffice.util.SecurityHelper;
import io.github.xbeeant.spring.mybatis.antdesign.PageRequest;
import io.github.xbeeant.spring.mybatis.antdesign.PageResponse;
import io.github.xbeeant.spring.mybatis.pagehelper.PageBounds;
import io.github.xbeeant.spring.security.LoginUser;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;

/**
 * @author xiaobiao
 * @version 2021/7/3
 */
@RestController
@RequestMapping("api/resource")
public class ResourceRestController {

    @Autowired
    private IResourcesService resourcesService;

    @Autowired
    private IResourcesVersionService resourcesVersionService;

    @Autowired
    private IDocTemplateService templateService;

    @Autowired
    private IAttachmentService attachmentService;

    @Autowired
    private IResourcesPermService resourcesPermService;

    @GetMapping(value = {"view"})
    public ApiResponse<Resources> view(Long rid) {

        LoginUser<User> userLoginUser = SecurityHelper.currentUser();

        ApiResponse<Resources> resourcesRst = resourcesService.selectByPrimaryKey(rid);
        if (!resourcesRst.getSuccess()) {
            return resourcesRst;
        }
        boolean hasPermission = resourcesService.hasPermission(resourcesRst.getData(), resourcesRst.getData().getFid(), Long.valueOf(userLoginUser.getUserId()));

        if (!hasPermission) {
            ApiResponse<Resources> result = new ApiResponse<>();
            result.setResult(401, "您无权查看此文档，请联系文档的作者：" + resourcesRst.getData().getUsername());
            return result;
        }

        return resourcesRst;
    }

    @GetMapping(value = {"", "/"})
    public ApiResponse<TableResponse<Resources>> table(Resources record, PageRequest pageRequest) {
        ApiResponse<TableResponse<Resources>> result = new ApiResponse<>();
        PageBounds pageBounds = pageRequest.getPageBounds();
        if (ObjectUtils.isEmpty(pageBounds.getOrders())) {
            pageBounds.setOrders("create_at desc");
        }
        LoginUser<User> userLoginUser = SecurityHelper.currentUser();

        record.setCreateBy(userLoginUser.getUserId());

        if (null == record.getDeleted()) {
            record.setDeleted(false);
        }

        ApiResponse<PageResponse<Resources>> pageResponseApiResponse = resourcesService.fuzzySearchByPagerIncludeSharedFolder(record, pageBounds);
        PageResponse<Resources> list = pageResponseApiResponse.getData();

        if (!pageResponseApiResponse.getSuccess()) {
            result.setResult(ErrorCodeConstant.NO_MATCH, ErrorCodeConstant.NO_MATCH_MSG);
            return result;
        }

        TableResponse<Resources> pageResponse = new TableResponse<>();
        pageResponse.setList(list);
        pageResponse.setPagination(list.getPagination());
        result.setData(pageResponse);
        return result;
    }

    @DeleteMapping("")
    public ApiResponse<String> delete(Long rid) {
        Resources record = new Resources();
        record.setDeleted(true);
        record.setRid(rid);
        resourcesService.updateByPrimaryKeySelective(record);

        return new ApiResponse<>();
    }

    @PostMapping()
    public ApiResponse<Resources> add(Long tid, Resources record) {
        // 根据模板id获取模板信息
        Attachment templateInfo = templateService.templateInfo(tid);

        LoginUser<User> userLoginUser = SecurityHelper.currentUser();
        record.setUsername(userLoginUser.getUserNickname());
        record.setUpdateAt(null);
        record.setCreateBy(userLoginUser.getUserId());
        record.setUpdateBy(userLoginUser.getUserId());
        record.setCreateAt(null);
        record.setSize(templateInfo.getFileSize());

        ApiResponse<Resources> result = resourcesService.insertSelective(record);
        Resources resource = result.getData();
        // 根据模板写入资源历史信息
        ResourcesVersion resourcesVersion = new ResourcesVersion();
        resourcesVersion.setRid(resource.getRid());
        resourcesVersion.setVname(resource.getName());
        resourcesVersion.setSize(resource.getSize());
        resourcesVersion.setType(resource.getType());
        resourcesVersion.setAid(templateInfo.getAid());
        resourcesVersionService.insertSelective(resourcesVersion);

        resourcesPermService.newResource(resource.getRid(), Long.valueOf(resource.getCreateBy()));
        return result;
    }


    @PostMapping("upload")
    public ApiResponse<String> upload(MultipartFile file, Resources record) throws IOException, NoSuchAlgorithmException {
        ApiResponse<String> result = new ApiResponse<>();

        LoginUser<User> user = SecurityHelper.currentUser();
        Attachment attachment = attachmentService.save(file, user.getUserId());
        String filename = file.getOriginalFilename();
        if (record.getRid() == null ) {
            // 新建资源文件
            // 写入资源的文件信息
            Resources resources = new Resources();
            resources.setName(filename);
            resources.setExt(attachment.getFileType());
            resources.setType("document");
            resources.setUsername(user.getUserNickname());
            resources.setSize(attachment.getFileSize());
            resources.setFid(record.getFid());
            resources.setCreateBy(user.getUserId());
            resourcesService.insertSelective(resources);

            // 记录资源和附件的关系
            ResourcesVersion resourcesVersion = new ResourcesVersion();
            resourcesVersion.setRid(resources.getRid());
            resourcesVersion.setAid(attachment.getAid());
            resourcesVersion.setSize(attachment.getFileSize());
            resourcesVersion.setType(attachment.getFileType());
            resourcesVersion.setVname(filename);
            resourcesVersion.setType(attachment.getFileType());
            resourcesVersion.setCreateBy(user.getUserId());
            resourcesVersion.setUpdateBy(user.getUserId());
            resourcesVersionService.insertSelective(resourcesVersion);

            resourcesPermService.newResource(resources.getRid(), Long.valueOf(user.getUserId()));
        } else {
            // 更新资源
            // 写入资源的文件信息
            Resources resources = new Resources();
            resources.setRid(record.getRid());
            resources.setName(filename);
            resources.setExt(attachment.getFileType());
            resources.setSize(attachment.getFileSize());
            resourcesService.updateByPrimaryKeySelective(resources);

            // 记录资源和附件的关系
            ResourcesVersion resourcesVersion = new ResourcesVersion();
            resourcesVersion.setRid(resources.getRid());
            resourcesVersion.setAid(attachment.getAid());
            resourcesVersion.setSize(attachment.getFileSize());
            resourcesVersion.setType(attachment.getFileType());
            resourcesVersion.setVname(filename);
            resourcesVersion.setType(attachment.getFileType());
            resourcesVersion.setCreateBy(user.getUserId());
            resourcesVersion.setUpdateBy(user.getUserId());
            resourcesVersionService.insertSelective(resourcesVersion);
        }

        return result;
    }

    @PostMapping("undel")
    public ApiResponse<String> unDelete(Long rid) {
        Resources record = new Resources();
        record.setDeleted(false);
        record.setRid(rid);
        resourcesService.updateByPrimaryKeySelective(record);

        return new ApiResponse<>();
    }
}
